package com.freely.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import org.apache.struts2.ServletActionContext;
import org.springframework.transaction.annotation.Transactional;

import com.freely.service.VerificationService;
import com.freely.util.CommonUtil;

@Transactional
public class VerificationServiceImpl implements VerificationService {
private static Properties pro = new Properties();
	
	static {
		InputStream input = UserServiceImpl.class.getClassLoader().getResourceAsStream("mail.properties");
		try {
			pro.load(input);
		} catch (IOException e) {
			throw new RuntimeException("文件不存在");
		}finally {
			if(input != null) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	

	/**
	 * 发送找回密码邮件
	 * @throws MessagingException 
	 */
	@Override
	public void sendMail(String email) throws MessagingException{
		String content = pro.getProperty("content");
		String verification_code = CommonUtil.randomNumber(6);
		content = MessageFormat.format(content,verification_code);
		Authenticator authenticator = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(pro.getProperty("account"), pro.getProperty("password"));
			}
		};
		Session session = Session.getInstance(pro, authenticator);
		MimeMessage message = new MimeMessage(session);
		message.setFrom(pro.getProperty("account"));
		message.setRecipients(RecipientType.TO, email);
		message.setSubject(pro.getProperty("subject"));
		message.setContent(pro.getProperty(content),pro.getProperty("type"));
		
		Transport.send(message);
		
		ServletActionContext.getServletContext().setAttribute(email,verification_code);
	}

}
